# core/queue_manager.py
import asyncio
import queue
import threading
import time
from utils.logger import setup_logger

logger = setup_logger("queue_manager")

class TaskQueueManager:
    def __init__(self, config, loop=None):
        self.task_queue = queue.Queue(maxsize=int(config['bilibili']['max_queue_size']))
        self.task_handler = None
        self.thread_pool = []
        self.running = False
        self.thread_count = int(config['system'].get('worker_threads', 2))
        self.loop = loop
        logger.info(f"任务队列初始化，最大长度: {self.task_queue.maxsize}, 工作线程: {self.thread_count}")
    
    def set_task_handler(self, handler):
        """设置任务处理函数"""
        self.task_handler = handler
    
    def add_task(self, user_id, text):
        """添加任务到队列"""
        try:
            self.task_queue.put((user_id, text), block=False)
            logger.debug(f"添加任务: {text[:20]}... (队列大小: {self.task_queue.qsize()})")
        except queue.Full:
            logger.warning("任务队列已满，丢弃新任务")
    
    def start(self):
        """启动工作线程"""
        if not self.task_handler:
            logger.error("无法启动队列管理器，未设置任务处理器")
            return
            
        self.running = True
        for i in range(self.thread_count):
            thread = threading.Thread(target=self._worker, daemon=True)
            thread.start()
            self.thread_pool.append(thread)
            logger.debug(f"启动工作线程 #{i+1}")
    
    def _worker(self):
        """工作线程函数"""
        while self.running:
            try:
                user_id, text = self.task_queue.get(timeout=1)
                logger.info(f"处理任务: {text[:20]}...")
                if asyncio.iscoroutinefunction(self.task_handler):
                    asyncio.run_coroutine_threadsafe(
                        self.task_handler(user_id, text), self.loop
                    )
                else:
                    self.task_handler(user_id, text)
                self.task_queue.task_done()
            except queue.Empty:
                continue
            except Exception as e:
                logger.error(f"任务处理异常: {e}")